﻿using UnityEngine;
using System.Collections;


/// <summary>
/// Controls the Player...
/// Player movement, shooting, health and shield.  
/// Quite standard nothing too elaborate nice simple approach for each.
/// Contains numerous tweakable variables.
/// </summary>
public class PlayerController : MonoBehaviour 
{
	public HealthBar healthBar;

	public AudioClip pewPew;
	public AudioClip ouch;
    public Transform Trnsfrm;
    public NavMesh.Node Node;
    NavMesh NavMsh;
    FrameFromDirection FFD;
    SpriteHotspot GunPoint; 

    public GameObject ShieldObject;

    int ohealthBar_healthWidth;
    void Awake() {
        ohealthBar_healthWidth = healthBar.healthWidth;
        Trnsfrm = transform;
        NavMsh = FindObjectOfType<NavMesh>();
        FFD = GetComponentInChildren<FrameFromDirection>();
        GunPoint = GetComponentInChildren<SpriteHotspot>();
    }


    public float speed;
    public int maxHealth;
    public int currentHealth;

    public GameObject Bullet;
    public GameObject Bullet2;
    public Transform BulletSpawn;

    public float fireRate;
    public float fireRate2;
    private float nextFire, nextFire2;


    float ShieldPower = 1.0f, ShieldCharge = 0;
    
    bool ShieldOn = false;


    void shoot(GameObject fab, float ang, bool side ) {

        transform.eulerAngles = new Vector3(0, 0, ang ); //lazy...
        var rot = BulletSpawn.rotation;
        transform.rotation = Quaternion.identity;
        GameObject go = Instantiate(fab, GunPoint.getWP(), rot) as GameObject;

        if(side) go.GetComponent<SpriteRenderer>().sortingOrder = -1;
    }
    void Update() {

        if(NavMsh != null) {
            var nNode = NavMsh.findNode(transform.position);
            if(nNode != null) Node = nNode;
        }

        var mPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        var vec = mPos - transform.position;
        float ang =  Mathf.Rad2Deg * Mathf.Atan2(vec.y, vec.x);

        FFD.set(ang);


        
        float deplete = Time.deltaTime;



        if(ShieldOn = ((ShieldOn && ShieldPower > deplete) || ShieldPower > 0.7f) && Input.GetButton("Jump")) {
            ShieldCharge = Mathf.Lerp(ShieldCharge, 3.0f + 0.5f* Mathf.Sin(Time.time * 16.0f), 6.0f * Time.deltaTime);
            ShieldObject.transform.localScale = Vector3.one * (3.0f + ShieldCharge);
            ShieldPower -= deplete;
            ShieldObject.SetActive(true);
        } else {
            ShieldCharge = Mathf.Lerp(ShieldCharge, 0.0f, 8.0f * Time.deltaTime);
            ShieldObject.transform.localScale = Vector3.one * (3.0f + ShieldCharge);
            if(ShieldCharge < 0.1f) {
                ShieldObject.SetActive(false);
                ShieldPower += Time.deltaTime*0.3f;
                if(ShieldPower > 1.0f) ShieldPower = 1.0f;
            }
        }

        if(ShieldCharge < 0.1f && Time.time > nextFire) {
            if(Input.GetButton("Fire2") && nextFire2 < Time.time ) {
                nextFire = Time.time + fireRate*2;
                nextFire2 = Time.time + fireRate2;
                transform.rotation = Quaternion.identity;
                shoot(Bullet2, ang + Random.Range(-5, 5), vec.y > 0);
				AudioSource.PlayClipAtPoint(pewPew, transform.position);
            } else if(Input.GetButton("Fire1")) {
                nextFire = Time.time + fireRate;
                shoot(Bullet, ang + Random.Range(-10, 10), vec.y > 0  );
            }

        }
        if(currentHealth <= 0) {
            //Destroy (gameObject);
            Application.LoadLevel(Application.loadedLevel);
        }
        if(currentHealth > maxHealth) {
            currentHealth = maxHealth;           
        }


        if( Input.GetKeyUp( KeyCode.Alpha1 )) {
            currentHealth = maxHealth;
            healthBar.healthWidth = ohealthBar_healthWidth;
        }
        if( Input.GetKeyUp( KeyCode.Alpha2 )) {
            var en = FindObjectsOfType<Ai>();
            foreach(Ai bot in en) {
                bot.damage(999999.0f);
            }
        }
    }
    void FixedUpdate() {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector2 movement = new Vector2(moveHorizontal, moveVertical);
        GetComponent<Rigidbody2D>().velocity = movement * speed;
    }

    void OnCollisionEnter2D(Collision2D other) {
        if(ShieldObject.activeSelf) return;
        var bot = other.gameObject.GetComponent<Ai>();
        if( bot != null && bot.enabled || other.gameObject.layer == LayerMask.NameToLayer("EnemyBullet") ) { //todo - lazy
            if(bot) bot.damage(20);
            else Destroy(other.gameObject);
            currentHealth--;
			healthBar.healthWidth -= healthBar.healthWidth/maxHealth;
			AudioSource.PlayClipAtPoint(ouch, transform.position);
        }
    }

    /*void OnGUI() {
        GUI.Box(new Rect(5, 5, Screen.width / 3 / (100 / maxHealth), 20), currentHealth + "/" + maxHealth);
    }*/
}
 